# 生产者代码，基本不变，只需将exchange_type改为topic（测试：python produce.py rabbitmq.red
# red color is my favorite
import json
import time
from typing import Optional

import pika
import sys

from loguru import logger


class Producer:
    def __init__(self, host: str, port: int = 5672, virtual_host: str = '/', username: str = 'guest',
                 password: str = 'guest', consumernums=1, *args, **kwargs):
        self.consumer_nums = consumernums
        self.connection = self._connect_mq(
            host, port, virtual_host, username, password)
        if self.connection:
            self.channel = self.connection.channel()
        # self.run_pro = Run_MUlPro(consumernums +2)
        self.exchange = kwargs['exchange'] if 'exchange' in kwargs else 'default_topic_messages'
        self.ack_objs = {}
        exchange_durable = kwargs['exchange_durable'] if 'exchange_durable' in kwargs else False
        self.channel.exchange_declare(
            exchange=self.exchange,
            exchange_type='topic',
            durable=exchange_durable
        )


    def _connect_mq(self, host: str, port: int = 5672, virtual_host: str = '/',
                    username: str = 'guest', password: str = 'guest') -> Optional[pika.BlockingConnection]:
        """connect to rabbitMQ.

        :params str host: host for rabbitMQ.
        :params int post: port for rabbitMQ, default is 5672.
        :params str virtual_host: virtual_host for rabbitMQ, default is '/'.
        :params str username: username for rabbit credential, default is 'guest'.
        :params str password: password for rabbit credential, default is 'guest'.

        :return: a BlockingConnection object or None
        """
        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(
                host, port, virtual_host, credentials)
            connection = pika.BlockingConnection(parameters)
            return connection
        except Exception as e:
            logger.error(f'RabbitMQ Connect failed: {e}')
            return None

    def __del__(self):
        self.connection.close()

    def add_message(self, body, routing_key):
        body = json.dumps(body).encode('utf-8')
        self.channel.basic_publish(exchange='topic_logs',
                              routing_key=routing_key,
                              body=body)

if __name__ == '__main__':
    producer = Producer(host='152.136.187.200', username='admin', password='admin', exchange='topic_logs')
    for i in range(100):
        producer.add_message('hello world %s' % i, 'ce.shi')